using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

namespace SP2010List404Handler.Features.ListBased404Handler
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("f03ebe5f-a849-4058-9729-d752008daf2f")]
    public class ListBased404HandlerEventReceiver : SPFeatureReceiver
    {

        private const string specified404Page = "Custom404Page.htm";
        private const string webAppPropertyForGuid = "URLRedirectListGuid";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;
            string urlRedirectListGuid = "";

            using (SPSite thisSite = thisWebApp.Sites[0])
            {
                using (SPWeb thisWeb = thisSite.RootWeb)
                {

                    try
                    {
                        SPList thisList = thisWeb.Lists["URL Redirect Matches"];
                        Guid thisListsGuid = thisList.ID;
                        urlRedirectListGuid = thisListsGuid.ToString();
                    }
                    catch (Exception ex)
                    {
                        throw new SPException("Couldn't find the List \"URL Redirect Matches\" in the web [" + thisWeb.Url + "].  Ensure the \"404 URL Redirect List\" feature has been activated on this web's site collection. Error: " + ex.Message);
                    }
                }

            }

            if (thisWebApp.Properties.ContainsKey("PreviousFileNotFoundPageSetting"))
                thisWebApp.Properties["PreviousFileNotFoundPageSetting"] = thisWebApp.FileNotFoundPage;
            else
                thisWebApp.Properties.Add("PreviousFileNotFoundPageSetting", thisWebApp.FileNotFoundPage);

            thisWebApp.FileNotFoundPage = specified404Page;

            if (thisWebApp.Properties.ContainsKey("Custom404Path"))
                thisWebApp.Properties["Custom404Path"] = specified404Page;
            else
                thisWebApp.Properties.Add("Custom404Path", specified404Page);
            if (urlRedirectListGuid != "")
                if (thisWebApp.Properties.ContainsKey(webAppPropertyForGuid))
                    thisWebApp.Properties[webAppPropertyForGuid] = urlRedirectListGuid;
                else
                    thisWebApp.Properties.Add(webAppPropertyForGuid, urlRedirectListGuid);


            thisWebApp.Update();
        }



        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;

            if (thisWebApp.Properties.ContainsKey("PreviousFileNotFoundPageSetting"))
            {
                thisWebApp.FileNotFoundPage = thisWebApp.Properties["PreviousFileNotFoundPageSetting"].ToString();
                thisWebApp.Properties.Remove("PreviousFileNotFoundPageSetting");
            }
            if (thisWebApp.Properties.ContainsKey("Custom404Path")) thisWebApp.Properties["Custom404Path"] = thisWebApp.FileNotFoundPage;
            thisWebApp.Update();

        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
